/**
 * 抗日战士 - 上海街头战斗游戏
 * 2D俯视角射击游戏
 */

// 道具类型枚举
const POWERUP_TYPES = {
  MEDKIT: 'medkit',           // 血包
  ADRENALINE: 'adrenaline',   // 肾上腺素
  BULLETPROOF_VEST: 'bulletproof_vest', // 防弹衣
  DYNAMITE_PACK: 'dynamite_pack',       // 炸药包
  INTELLIGENCE_FILE: 'intelligence_file' // 情报文件
};

// 道具配置
const POWERUP_CONFIG = {
  [POWERUP_TYPES.MEDKIT]: {
    name: '血包',
    icon: '❤️',
    color: '#e74c3c',
    description: '恢复1点生命值',
    sound: 'heartbeat'
  },
  [POWERUP_TYPES.ADRENALINE]: {
    name: '肾上腺素',
    icon: '💉',
    color: '#3498db',
    description: '射速提升200%',
    sound: 'injection'
  },
  [POWERUP_TYPES.BULLETPROOF_VEST]: {
    name: '防弹衣',
    icon: '🛡️',
    color: '#27ae60',
    description: '获得1次伤害免疫',
    sound: 'metal'
  },
  [POWERUP_TYPES.DYNAMITE_PACK]: {
    name: '炸药包',
    icon: '💥',
    color: '#f39c12',
    description: '下次射击引发爆炸',
    sound: 'fuse'
  },
  [POWERUP_TYPES.INTELLIGENCE_FILE]: {
    name: '情报文件',
    icon: '📄',
    color: '#8b4513',
    description: '立即增加200分',
    sound: 'paper'
  }
};

class AntiJapaneseWarrior {
  constructor() {
    // 游戏画布和上下文
    this.canvas = document.getElementById('gameCanvas');
    this.ctx = this.canvas.getContext('2d');

    // 音频元素
    this.audioElements = {
      bgm: new Audio('vedio/game_bgm.mp3'),
      gun: new Audio('vedio/gun.MP3'),
      powerup: new Audio('vedio/obgs.MP3')
    };

    // 设置背景音乐属性
    this.audioElements.bgm.loop = true;
    this.audioElements.bgm.volume = 0.3;

    // 设置音效属性
    this.audioElements.gun.volume = 0.2;
    this.audioElements.powerup.volume = 0.4;

    // 游戏状态
    this.gameState = 'start'; // start, playing, paused, gameOver
    this.score = 0;
    this.lives = 3;
    this.grenades = 3;

    // 游戏对象
    this.player = null;
    this.enemies = [];
    this.bullets = [];
    this.powerUps = [];
    this.explosions = [];
    this.bulletTrails = [];

    // 输入控制
    this.keys = {};
    this.mouse = { x: 0, y: 0 };
    this.mousePressed = false;

    // 游戏参数
    this.enemySpawnRate = 2000; // 敌人生成间隔(ms)
    this.lastEnemySpawn = 0;
    this.shootCooldown = 300; // 射击冷却时间(ms)
    this.lastShootTime = 0;
    this.baseShootCooldown = 300; // 基础射击冷却时间
    this.difficultyIncrease = 200; // 每200分增加难度
    this.bossScore = 1000; // Boss出现分数

    // 道具强化状态管理
    this.powerUpStates = {
      adrenaline: {
        active: false,
        endTime: 0,
        duration: 10000 // 10秒
      },
      bulletproofVest: {
        active: false
      },
      dynamitePack: {
        active: false
      }
    };

    // 道具生成参数
    this.powerUpSpawnChance = 0.15; // 基础15%概率
    this.officerPowerUpChance = 0.25; // 军官25%概率
    this.intelligenceChance = 0.05; // 情报文件5%概率

    // 视觉效果
    this.pickupPrompts = []; // 拾取提示
    this.playerEffects = {
      adrenalineGlow: 0,
      shieldIcon: false,
      dynamiteMuzzle: false
    };

    // 初始化游戏
    this.init();
  }

  /**
   * 初始化游戏
   */
  init() {
    this.setupEventListeners();
    this.createPlayer();
    this.showStartScreen();
  }

  /**
   * 设置事件监听器
   */
  setupEventListeners() {
    // 键盘事件
    document.addEventListener('keydown', (e) => {
      this.keys[e.code] = true;

      // 空格键投掷手雷
      if (e.code === 'Space' && this.gameState === 'playing') {
        this.throwGrenade();
      }

      // ESC键暂停/继续
      if (e.code === 'Escape' && this.gameState === 'playing') {
        this.togglePause();
      }
    });

    document.addEventListener('keyup', (e) => {
      this.keys[e.code] = false;
    });

    // 鼠标事件
    this.canvas.addEventListener('mousemove', (e) => {
      const rect = this.canvas.getBoundingClientRect();
      this.mouse.x = e.clientX - rect.left;
      this.mouse.y = e.clientY - rect.top;
    });

    this.canvas.addEventListener('mousedown', (e) => {
      this.mousePressed = true;
      if (this.gameState === 'playing') {
        this.shoot();
      }
    });

    this.canvas.addEventListener('mouseup', () => {
      this.mousePressed = false;
    });

    // 游戏控制按钮
    document.getElementById('startBtn').addEventListener('click', () => {
      this.startGame();
    });

    document.getElementById('restartBtn').addEventListener('click', () => {
      this.restartGame();
    });
  }

  /**
   * 创建玩家角色
   */
  createPlayer() {
    this.player = {
      x: this.canvas.width / 2,
      y: this.canvas.height - 100,
      width: 30,
      height: 40,
      speed: 3,
      health: 3,
      direction: 1, // 1为右，-1为左
      animationFrame: 0,
      lastAnimationUpdate: 0
    };
  }

  /**
   * 显示开始界面
   */
  showStartScreen() {
    this.gameState = 'start';
    document.getElementById('startScreen').classList.remove('hidden');
    document.getElementById('gameOverScreen').classList.add('hidden');
    document.getElementById('pauseScreen').classList.add('hidden');
  }

  /**
   * 开始游戏
   */
  startGame() {
    this.gameState = 'playing';
    this.score = 0;
    this.lives = 3;
    this.grenades = 3;
    this.enemies = [];
    this.bullets = [];
    this.powerUps = [];
    this.explosions = [];
    this.bulletTrails = [];
    this.enemySpawnRate = 2000;
    this.lastEnemySpawn = 0;

    // 重置玩家位置
    this.player.x = this.canvas.width / 2;
    this.player.y = this.canvas.height - 100;
    this.player.health = 3;

    // 播放背景音乐
    this.playSound('bgm');

    // 隐藏界面
    document.getElementById('startScreen').classList.add('hidden');
    document.getElementById('gameOverScreen').classList.add('hidden');
    document.getElementById('pauseScreen').classList.add('hidden');

    // 开始游戏循环
    this.gameLoop();
  }

  /**
   * 切换暂停状态
   */
  togglePause() {
    if (this.gameState === 'playing') {
      this.gameState = 'paused';
      document.getElementById('pauseScreen').classList.remove('hidden');
      // 暂停背景音乐
      this.audioElements.bgm.pause();
    } else if (this.gameState === 'paused') {
      this.gameState = 'playing';
      document.getElementById('pauseScreen').classList.add('hidden');
      // 恢复背景音乐
      const playPromise = this.audioElements.bgm.play();
      if (playPromise !== undefined) {
        playPromise.catch(error => {
          console.log('背景音乐播放失败:', error);
        });
      }
      this.gameLoop();
    }
  }

  /**
   * 重新开始游戏
   */
  restartGame() {
    this.score = 0;
    this.lives = 3;
    this.grenades = 3;
    this.enemySpawnRate = 2000;
    this.shootCooldown = 300;
    this.baseShootCooldown = 300;
    this.lastShootTime = 0;
    this.lastEnemySpawn = 0;
    this.enemies = [];
    this.bullets = [];
    this.powerUps = [];
    this.explosions = [];
    this.bulletTrails = [];
    this.pickupPrompts = [];

    // 重置道具强化状态
    this.powerUpStates = {
      adrenaline: {
        active: false,
        endTime: 0,
        duration: 10000
      },
      bulletproofVest: {
        active: false
      },
      dynamitePack: {
        active: false
      }
    };

    // 重置视觉效果
    this.playerEffects = {
      adrenalineGlow: 0,
      shieldIcon: false,
      dynamiteMuzzle: false
    };

    this.createPlayer();
    this.showStartScreen();
  }

  /**
   * 游戏结束
   */
  gameOver() {
    this.gameState = 'gameOver';
    document.getElementById('finalScore').textContent = this.score;
    document.getElementById('gameOverScreen').classList.remove('hidden');

    // 停止背景音乐
    this.audioElements.bgm.pause();
    this.audioElements.bgm.currentTime = 0;
  }

  /**
   * 游戏主循环
   */
  gameLoop() {
    if (this.gameState !== 'playing') return;

    this.update();
    this.render();

    requestAnimationFrame(() => this.gameLoop());
  }

  /**
   * 更新游戏状态
   */
  update() {
    this.updatePlayer();
    this.updateEnemies();
    this.updateBullets();
    this.updatePowerUps();
    this.updatePowerUpStates();
    this.updatePickupPrompts();
    this.updateExplosions();
    this.updateBulletTrails();
    this.spawnEnemies();
    this.checkCollisions();
    this.updateUI();
    this.updateDifficulty();
  }

  /**
   * 更新玩家状态
   */
  updatePlayer() {
    // 移动控制
    if (this.keys['KeyW'] || this.keys['ArrowUp']) {
      this.player.y = Math.max(50, this.player.y - this.player.speed);
    }
    if (this.keys['KeyS'] || this.keys['ArrowDown']) {
      this.player.y = Math.min(this.canvas.height - 50, this.player.y + this.player.speed);
    }
    if (this.keys['KeyA'] || this.keys['ArrowLeft']) {
      this.player.x = Math.max(15, this.player.x - this.player.speed);
      this.player.direction = -1;
    }
    if (this.keys['KeyD'] || this.keys['ArrowRight']) {
      this.player.x = Math.min(this.canvas.width - 15, this.player.x + this.player.speed);
      this.player.direction = 1;
    }

    // 动画更新
    if (Date.now() - this.player.lastAnimationUpdate > 100) {
      this.player.animationFrame = (this.player.animationFrame + 1) % 4;
      this.player.lastAnimationUpdate = Date.now();
    }

    // 自动射击
    if (this.mousePressed && Date.now() - this.lastShootTime > this.shootCooldown) {
      this.shoot();
    }
  }

  /**
   * 射击
   */
  shoot() {
    if (Date.now() - this.lastShootTime < this.shootCooldown) return;

    this.lastShootTime = Date.now();

    // 检查是否有炸药包效果
    const hasDynamite = this.powerUpStates.dynamitePack.active;

    // 计算射击方向
    const dx = this.mouse.x - this.player.x;
    const dy = this.mouse.y - this.player.y;
    const distance = Math.sqrt(dx * dx + dy * dy);

    if (distance === 0) return;

    const speed = 8;
    const bullet = {
      x: this.player.x,
      y: this.player.y,
      vx: (dx / distance) * speed,
      vy: (dy / distance) * speed,
      radius: 3,
      life: 60, // 子弹存活帧数
      isDynamite: hasDynamite // 标记是否为爆炸子弹
    };

    this.bullets.push(bullet);

    // 播放枪声音效
    this.playSound('gun');

    // 创建子弹轨迹效果
    this.createBulletTrail(this.player.x, this.player.y, dx / distance, dy / distance);

    // 如果使用了炸药包，重置状态
    if (hasDynamite) {
      this.powerUpStates.dynamitePack.active = false;
      this.playerEffects.dynamiteMuzzle = false;
    }
  }

  /**
   * 投掷手雷
   */
  throwGrenade() {
    if (this.grenades <= 0) return;

    this.grenades--;

    // 清除所有敌人
    this.enemies.forEach(enemy => {
      this.createExplosion(enemy.x, enemy.y);
    });
    this.enemies = [];

    // 清除所有道具
    this.powerUps = [];

    this.updateUI();
  }

  /**
   * 生成敌人
   */
  spawnEnemies() {
    const now = Date.now();
    if (now - this.lastEnemySpawn > this.enemySpawnRate) {
      this.lastEnemySpawn = now;

      // 随机选择敌人类型
      const enemyTypes = ['infantry', 'officer', 'tank'];
      const weights = [0.6, 0.3, 0.1]; // 步兵60%，军官30%，坦克10%

      let random = Math.random();
      let enemyType = 'infantry';

      for (let i = 0; i < weights.length; i++) {
        random -= weights[i];
        if (random <= 0) {
          enemyType = enemyTypes[i];
          break;
        }
      }

      // Boss战
      if (this.score >= this.bossScore && this.score % this.bossScore === 0) {
        enemyType = 'boss';
      }

      const enemy = this.createEnemy(enemyType);
      this.enemies.push(enemy);
    }
  }

  /**
   * 创建敌人
   */
  createEnemy(type) {
    const x = Math.random() * (this.canvas.width - 60) + 30;
    const y = -50;

    let enemy = {
      x: x,
      y: y,
      type: type,
      width: 30,
      height: 40,
      health: 1,
      maxHealth: 1,
      speed: 1,
      score: 10
    };

    switch (type) {
      case 'infantry':
        enemy.speed = 1;
        enemy.health = enemy.maxHealth = 1;
        enemy.score = 10;
        break;
      case 'officer':
        enemy.speed = 2;
        enemy.health = enemy.maxHealth = 2;
        enemy.score = 20;
        break;
      case 'tank':
        enemy.speed = 0.5;
        enemy.health = enemy.maxHealth = 5;
        enemy.score = 50;
        enemy.width = 50;
        enemy.height = 60;
        break;
      case 'boss':
        enemy.speed = 0.3;
        enemy.health = enemy.maxHealth = 10;
        enemy.score = 200;
        enemy.width = 80;
        enemy.height = 100;
        break;
    }

    return enemy;
  }

  /**
   * 更新敌人状态
   */
  updateEnemies() {
    for (let i = this.enemies.length - 1; i >= 0; i--) {
      const enemy = this.enemies[i];

      // 移动敌人
      enemy.y += enemy.speed;

      // 移除超出屏幕的敌人
      if (enemy.y > this.canvas.height + 50) {
        this.enemies.splice(i, 1);
      }
    }
  }

  /**
   * 更新子弹状态
   */
  updateBullets() {
    for (let i = this.bullets.length - 1; i >= 0; i--) {
      const bullet = this.bullets[i];

      // 移动子弹
      bullet.x += bullet.vx;
      bullet.y += bullet.vy;
      bullet.life--;

      // 移除超出屏幕或生命耗尽的子弹
      if (bullet.life <= 0 ||
        bullet.x < 0 || bullet.x > this.canvas.width ||
        bullet.y < 0 || bullet.y > this.canvas.height) {
        this.bullets.splice(i, 1);
      }
    }
  }

  /**
   * 更新道具状态
   */
  updatePowerUps() {
    for (let i = this.powerUps.length - 1; i >= 0; i--) {
      const powerUp = this.powerUps[i];

      // 移动道具（缓慢下落模拟重力）
      powerUp.y += 0.5;

      // 更新道具生命周期
      powerUp.lifeTime += 16; // 假设60FPS

      // 道具闪烁预警（最后3秒）
      if (powerUp.lifeTime > 5000 && powerUp.lifeTime < 8000) {
        powerUp.flash = Math.sin(powerUp.lifeTime * 0.01) > 0;
      }

      // 移除超出屏幕或过期的道具
      if (powerUp.y > this.canvas.height + 30 || powerUp.lifeTime >= 8000) {
        this.powerUps.splice(i, 1);
      }
    }
  }

  /**
   * 更新道具强化状态
   */
  updatePowerUpStates() {
    const currentTime = Date.now();

    // 更新肾上腺素状态
    if (this.powerUpStates.adrenaline.active && currentTime >= this.powerUpStates.adrenaline.endTime) {
      this.powerUpStates.adrenaline.active = false;
      this.shootCooldown = this.baseShootCooldown;
      this.playerEffects.adrenalineGlow = 0;
    }

    // 更新肾上腺素视觉效果
    if (this.powerUpStates.adrenaline.active) {
      this.playerEffects.adrenalineGlow = Math.sin(currentTime * 0.005) * 0.3 + 0.7;
    }

    // 更新防弹衣视觉效果
    this.playerEffects.shieldIcon = this.powerUpStates.bulletproofVest.active;

    // 更新炸药包视觉效果
    this.playerEffects.dynamiteMuzzle = this.powerUpStates.dynamitePack.active;
  }

  /**
   * 更新拾取提示
   */
  updatePickupPrompts() {
    for (let i = this.pickupPrompts.length - 1; i >= 0; i--) {
      const prompt = this.pickupPrompts[i];
      prompt.lifeTime += 16;

      if (prompt.lifeTime >= 2000) { // 2秒后消失
        this.pickupPrompts.splice(i, 1);
      }
    }
  }

  /**
   * 更新爆炸效果
   */
  updateExplosions() {
    for (let i = this.explosions.length - 1; i >= 0; i--) {
      const explosion = this.explosions[i];
      explosion.life--;

      if (explosion.life <= 0) {
        this.explosions.splice(i, 1);
      }
    }
  }

  /**
   * 更新子弹轨迹
   */
  updateBulletTrails() {
    for (let i = this.bulletTrails.length - 1; i >= 0; i--) {
      const trail = this.bulletTrails[i];
      trail.life--;

      if (trail.life <= 0) {
        this.bulletTrails.splice(i, 1);
      }
    }
  }

  /**
   * 碰撞检测
   */
  checkCollisions() {
    // 子弹与敌人碰撞
    for (let i = this.bullets.length - 1; i >= 0; i--) {
      const bullet = this.bullets[i];

      for (let j = this.enemies.length - 1; j >= 0; j--) {
        const enemy = this.enemies[j];

        const distance = Math.sqrt(
          Math.pow(bullet.x - enemy.x, 2) +
          Math.pow(bullet.y - enemy.y, 2)
        );

        if (distance < bullet.radius + enemy.width / 2) {
          // 敌人受伤
          enemy.health--;

          // 移除子弹
          this.bullets.splice(i, 1);

          // 创建爆炸效果
          this.createExplosion(enemy.x, enemy.y);

          // 检查是否为爆炸子弹
          if (bullet.isDynamite) {
            // 爆炸范围伤害
            this.explodeAtPosition(bullet.x, bullet.y, 150);
          }

          // 敌人死亡
          if (enemy.health <= 0) {
            this.score += enemy.score;
            this.enemies.splice(j, 1);

            // 根据敌人类型决定道具掉落概率
            let dropChance = this.powerUpSpawnChance;
            if (enemy.type === 'officer' || enemy.type === 'tank') {
              dropChance = this.officerPowerUpChance;
            }

            // 随机掉落道具
            if (Math.random() < dropChance) {
              this.spawnPowerUp(enemy.x, enemy.y, enemy.type);
            }
          }

          break;
        }
      }
    }

    // 玩家与敌人碰撞
    for (let i = this.enemies.length - 1; i >= 0; i--) {
      const enemy = this.enemies[i];

      if (this.checkRectCollision(this.player, enemy)) {
        // 检查是否有防弹衣保护
        if (this.powerUpStates.bulletproofVest.active) {
          this.powerUpStates.bulletproofVest.active = false;
          this.playerEffects.shieldIcon = false;
        } else {
          this.player.health--;
        }

        this.enemies.splice(i, 1);
        this.createExplosion(enemy.x, enemy.y);

        if (this.player.health <= 0) {
          this.gameOver();
          return;
        }
      }
    }

    // 玩家与道具碰撞（扩大碰撞检测半径20%）
    for (let i = this.powerUps.length - 1; i >= 0; i--) {
      const powerUp = this.powerUps[i];

      // 扩大碰撞检测范围
      const expandedPlayer = {
        x: this.player.x - this.player.width * 0.1,
        y: this.player.y - this.player.height * 0.1,
        width: this.player.width * 1.2,
        height: this.player.height * 1.2
      };

      if (this.checkRectCollision(expandedPlayer, powerUp)) {
        this.applyPowerUp(powerUp.type);
        this.powerUps.splice(i, 1);
      }
    }
  }

  /**
   * 在指定位置产生爆炸效果
   */
  explodeAtPosition(x, y, radius) {
    // 对范围内的所有敌人造成伤害
    this.enemies.forEach(enemy => {
      const distance = Math.sqrt(
        Math.pow(x - enemy.x, 2) + Math.pow(y - enemy.y, 2)
      );

      if (distance <= radius) {
        enemy.health -= 3; // 爆炸造成3点伤害

        if (enemy.health <= 0) {
          this.score += enemy.score;
          this.createExplosion(enemy.x, enemy.y);
        }
      }
    });

    // 移除死亡的敌人
    this.enemies = this.enemies.filter(enemy => enemy.health > 0);

    // 创建大爆炸效果
    this.createExplosion(x, y);
  }

  /**
   * 矩形碰撞检测
   */
  checkRectCollision(rect1, rect2) {
    return rect1.x < rect2.x + rect2.width &&
      rect1.x + rect1.width > rect2.x &&
      rect1.y < rect2.y + rect2.height &&
      rect1.y + rect1.height > rect2.y;
  }

  /**
   * 创建爆炸效果
   */
  createExplosion(x, y) {
    this.explosions.push({
      x: x,
      y: y,
      life: 20,
      maxLife: 20
    });
  }

  /**
   * 创建子弹轨迹
   */
  createBulletTrail(x, y, dx, dy) {
    this.bulletTrails.push({
      x: x,
      y: y,
      dx: dx,
      dy: dy,
      life: 10
    });
  }

  /**
   * 生成道具
   */
  spawnPowerUp(x, y, enemyType = null) {
    // 情报文件只能从军官掉落
    if (enemyType === 'officer' && Math.random() < this.intelligenceChance) {
      this.createPowerUpObject(x, y, POWERUP_TYPES.INTELLIGENCE_FILE);
      return;
    }

    // 其他道具类型
    let availableTypes = [
      POWERUP_TYPES.MEDKIT,
      POWERUP_TYPES.ADRENALINE,
      POWERUP_TYPES.BULLETPROOF_VEST,
      POWERUP_TYPES.DYNAMITE_PACK
    ];

    // 检查冲突规则：如果已有防弹衣，移除防弹衣选项
    if (this.powerUpStates.bulletproofVest.active) {
      availableTypes = availableTypes.filter(t => t !== POWERUP_TYPES.BULLETPROOF_VEST);
    }

    // 随机选择道具类型
    if (availableTypes.length > 0) {
      const type = availableTypes[Math.floor(Math.random() * availableTypes.length)];
      this.createPowerUpObject(x, y, type);
    }
  }

  /**
   * 创建道具对象
   */
  createPowerUpObject(x, y, type) {
    this.powerUps.push({
      x: x - 15,
      y: y,
      width: 30,
      height: 30,
      type: type,
      lifeTime: 0,
      flash: false
    });
  }

  /**
   * 应用道具效果
   */
  applyPowerUp(type) {
    const config = POWERUP_CONFIG[type];
    if (!config) return;

    switch (type) {
      case POWERUP_TYPES.MEDKIT:
        if (this.player.health >= 3) {
          // 如果生命值已满，转换为分数
          this.score += 50;
          this.showPickupPrompt('生命已满！+50分', '#e74c3c');
        } else {
          this.player.health = Math.min(3, this.player.health + 1);
          this.showPickupPrompt('生命恢复！', '#e74c3c');
        }
        break;

      case POWERUP_TYPES.ADRENALINE:
        // 激活肾上腺素效果
        this.powerUpStates.adrenaline.active = true;
        this.powerUpStates.adrenaline.endTime = Date.now() + this.powerUpStates.adrenaline.duration;
        this.shootCooldown = 100; // 0.1秒/发
        this.showPickupPrompt('射速提升！', '#3498db');
        break;

      case POWERUP_TYPES.BULLETPROOF_VEST:
        this.powerUpStates.bulletproofVest.active = true;
        this.showPickupPrompt('防弹衣装备！', '#27ae60');
        break;

      case POWERUP_TYPES.DYNAMITE_PACK:
        this.powerUpStates.dynamitePack.active = true;
        this.showPickupPrompt('爆炸武装！', '#f39c12');
        break;

      case POWERUP_TYPES.INTELLIGENCE_FILE:
        this.score += 200;
        this.showPickupPrompt('情报获得！+200分', '#8b4513');
        break;
    }

    // 播放道具音效
    this.playSound('powerup');
  }

  /**
   * 显示拾取提示
   */
  showPickupPrompt(text, color) {
    this.pickupPrompts.push({
      text: text,
      color: color,
      lifeTime: 0,
      x: this.canvas.width / 2,
      y: this.canvas.height / 2 - 50
    });
  }

  /**
   * 播放音效
   * @param {string} soundType - 音效类型 ('bgm', 'gun', 'powerup')
   */
  playSound(soundType) {
    try {
      switch (soundType) {
        case 'bgm':
          // 播放背景音乐
          this.audioElements.bgm.currentTime = 0;
          const playPromise = this.audioElements.bgm.play();
          if (playPromise !== undefined) {
            playPromise.catch(error => {
              console.log('背景音乐播放失败:', error);
            });
          }
          break;

        case 'gun':
          // 播放枪声
          const gunSound = this.audioElements.gun.cloneNode();
          gunSound.volume = this.audioElements.gun.volume;
          const gunPromise = gunSound.play();
          if (gunPromise !== undefined) {
            gunPromise.catch(error => {
              console.log('枪声播放失败:', error);
            });
          }
          break;

        case 'powerup':
          // 播放道具音效
          const powerupSound = this.audioElements.powerup.cloneNode();
          powerupSound.volume = this.audioElements.powerup.volume;
          const powerupPromise = powerupSound.play();
          if (powerupPromise !== undefined) {
            powerupPromise.catch(error => {
              console.log('道具音效播放失败:', error);
            });
          }
          break;

        default:
          console.log(`未知音效类型: ${soundType}`);
      }
    } catch (error) {
      console.log(`音效播放出错: ${error}`);
    }
  }

  /**
   * 更新难度
   */
  updateDifficulty() {
    const difficultyLevel = Math.floor(this.score / this.difficultyIncrease);
    this.enemySpawnRate = Math.max(500, 2000 - difficultyLevel * 200);
  }

  /**
   * 更新UI
   */
  updateUI() {
    document.getElementById('score').textContent = this.score;
    document.getElementById('lives').textContent = '❤️'.repeat(this.player.health);
    document.getElementById('grenades').textContent = `💣 x${this.grenades}`;

    // 更新道具强化状态显示
    this.updatePowerUpStatusUI();
  }

  /**
   * 更新道具强化状态UI
   */
  updatePowerUpStatusUI() {
    // 肾上腺素状态
    if (this.powerUpStates.adrenaline.active) {
      const remainingTime = Math.max(0, this.powerUpStates.adrenaline.endTime - Date.now());
      const progress = remainingTime / this.powerUpStates.adrenaline.duration;

      // 更新进度条
      const progressElement = document.querySelector('#adrenalineStatus .powerup-progress');
      if (progressElement) {
        progressElement.style.width = `${progress * 100}%`;
      }

      // 更新时间文本
      const textElement = document.querySelector('#adrenalineStatus .powerup-text');
      if (textElement) {
        textElement.textContent = `肾上腺素 (${Math.ceil(remainingTime / 1000)}s)`;
      }

      document.getElementById('adrenalineStatus').style.display = 'block';
    } else {
      document.getElementById('adrenalineStatus').style.display = 'none';
    }

    // 防弹衣状态
    if (this.powerUpStates.bulletproofVest.active) {
      document.getElementById('vestStatus').style.display = 'block';
    } else {
      document.getElementById('vestStatus').style.display = 'none';
    }

    // 炸药包状态
    if (this.powerUpStates.dynamitePack.active) {
      document.getElementById('dynamiteStatus').style.display = 'block';
    } else {
      document.getElementById('dynamiteStatus').style.display = 'none';
    }
  }

  /**
   * 渲染游戏
   */
  render() {
    // 清空画布
    this.ctx.fillStyle = '#34495e';
    this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);

    // 绘制背景网格
    this.drawGrid();

    // 绘制游戏对象
    this.drawPlayer();
    this.drawEnemies();
    this.drawBullets();
    this.drawPowerUps();
    this.drawExplosions();
    this.drawBulletTrails();
    this.drawPickupPrompts();

    // 绘制准星
    this.drawCrosshair();
  }

  /**
   * 绘制背景网格
   */
  drawGrid() {
    this.ctx.strokeStyle = 'rgba(255, 255, 255, 0.1)';
    this.ctx.lineWidth = 1;

    for (let x = 0; x < this.canvas.width; x += 50) {
      this.ctx.beginPath();
      this.ctx.moveTo(x, 0);
      this.ctx.lineTo(x, this.canvas.height);
      this.ctx.stroke();
    }

    for (let y = 0; y < this.canvas.height; y += 50) {
      this.ctx.beginPath();
      this.ctx.moveTo(0, y);
      this.ctx.lineTo(this.canvas.width, y);
      this.ctx.stroke();
    }
  }

  /**
   * 绘制玩家
   */
  drawPlayer() {
    this.ctx.save();
    this.ctx.translate(this.player.x, this.player.y);

    // 根据方向翻转
    if (this.player.direction === -1) {
      this.ctx.scale(-1, 1);
    }

    // 绘制肾上腺素效果（蓝光脉冲）
    if (this.playerEffects.adrenalineGlow > 0) {
      this.ctx.save();
      this.ctx.globalAlpha = this.playerEffects.adrenalineGlow * 0.5;
      this.ctx.strokeStyle = '#3498db';
      this.ctx.lineWidth = 3;
      this.ctx.beginPath();
      this.ctx.arc(0, 0, 35, 0, Math.PI * 2);
      this.ctx.stroke();
      this.ctx.restore();
    }

    // 绘制玩家身体
    this.ctx.fillStyle = '#3498db';
    this.ctx.fillRect(-this.player.width / 2, -this.player.height / 2,
      this.player.width, this.player.height);

    // 绘制玩家头部
    this.ctx.fillStyle = '#f39c12';
    this.ctx.beginPath();
    this.ctx.arc(0, -this.player.height / 2 - 10, 8, 0, Math.PI * 2);
    this.ctx.fill();

    // 绘制武器（炸药包时变为橙色）
    this.ctx.fillStyle = this.playerEffects.dynamiteMuzzle ? '#f39c12' : '#2c3e50';
    this.ctx.fillRect(this.player.width / 2 - 5, -2, 15, 4);

    // 绘制防弹衣图标
    if (this.playerEffects.shieldIcon) {
      this.ctx.save();
      this.ctx.globalAlpha = 0.7;
      this.ctx.font = '16px Arial';
      this.ctx.fillStyle = '#27ae60';
      this.ctx.textAlign = 'center';
      this.ctx.textBaseline = 'middle';
      this.ctx.fillText('🛡️', 0, -this.player.height / 2 - 25);
      this.ctx.restore();
    }

    this.ctx.restore();
  }

  /**
   * 绘制敌人
   */
  drawEnemies() {
    this.enemies.forEach(enemy => {
      this.ctx.save();
      this.ctx.translate(enemy.x, enemy.y);

      // 根据敌人类型绘制不同颜色
      let color = '#e74c3c';
      switch (enemy.type) {
        case 'infantry':
          color = '#e74c3c';
          break;
        case 'officer':
          color = '#9b59b6';
          break;
        case 'tank':
          color = '#34495e';
          break;
        case 'boss':
          color = '#c0392b';
          break;
      }

      // 绘制敌人身体
      this.ctx.fillStyle = color;
      this.ctx.fillRect(-enemy.width / 2, -enemy.height / 2,
        enemy.width, enemy.height);

      // 绘制敌人头部
      this.ctx.fillStyle = '#ecf0f1';
      this.ctx.beginPath();
      this.ctx.arc(0, -enemy.height / 2 - 8, 6, 0, Math.PI * 2);
      this.ctx.fill();

      // 绘制血条
      if (enemy.maxHealth > 1) {
        const barWidth = enemy.width;
        const barHeight = 4;
        const healthPercent = enemy.health / enemy.maxHealth;

        this.ctx.fillStyle = '#e74c3c';
        this.ctx.fillRect(-barWidth / 2, -enemy.height / 2 - 15, barWidth, barHeight);

        this.ctx.fillStyle = '#27ae60';
        this.ctx.fillRect(-barWidth / 2, -enemy.height / 2 - 15,
          barWidth * healthPercent, barHeight);
      }

      this.ctx.restore();
    });
  }

  /**
   * 绘制子弹
   */
  drawBullets() {
    this.ctx.fillStyle = '#f39c12';
    this.bullets.forEach(bullet => {
      this.ctx.beginPath();
      this.ctx.arc(bullet.x, bullet.y, bullet.radius, 0, Math.PI * 2);
      this.ctx.fill();
    });
  }

  /**
   * 绘制道具
   */
  drawPowerUps() {
    this.powerUps.forEach(powerUp => {
      this.ctx.save();
      this.ctx.translate(powerUp.x + powerUp.width / 2, powerUp.y + powerUp.height / 2);

      const config = POWERUP_CONFIG[powerUp.type];
      if (!config) return;

      // 处理闪烁效果
      if (powerUp.flash) {
        this.ctx.globalAlpha = 0.5;
      }

      // 绘制道具背景
      this.ctx.fillStyle = config.color;
      this.ctx.fillRect(-powerUp.width / 2, -powerUp.height / 2,
        powerUp.width, powerUp.height);

      // 绘制道具图标
      this.ctx.font = '16px Arial';
      this.ctx.fillStyle = 'white';
      this.ctx.textAlign = 'center';
      this.ctx.textBaseline = 'middle';
      this.ctx.fillText(config.icon, 0, 0);

      this.ctx.restore();
    });
  }

  /**
   * 绘制拾取提示
   */
  drawPickupPrompts() {
    this.pickupPrompts.forEach(prompt => {
      const alpha = Math.max(0, 1 - prompt.lifeTime / 2000);
      this.ctx.save();
      this.ctx.globalAlpha = alpha;

      // 绘制背景
      this.ctx.fillStyle = 'rgba(0, 0, 0, 0.7)';
      this.ctx.fillRect(prompt.x - 100, prompt.y - 20, 200, 40);

      // 绘制文字
      this.ctx.font = 'bold 18px Arial';
      this.ctx.fillStyle = prompt.color;
      this.ctx.textAlign = 'center';
      this.ctx.textBaseline = 'middle';
      this.ctx.fillText(prompt.text, prompt.x, prompt.y);

      // 绘制箭头
      this.ctx.fillStyle = prompt.color;
      this.ctx.font = '24px Arial';
      this.ctx.fillText('↑', prompt.x, prompt.y + 30);

      this.ctx.restore();
    });
  }

  /**
   * 绘制爆炸效果
   */
  drawExplosions() {
    this.explosions.forEach(explosion => {
      const alpha = explosion.life / explosion.maxLife;
      const size = (1 - alpha) * 50 + 10;

      this.ctx.save();
      this.ctx.globalAlpha = alpha;

      // 绘制爆炸圆圈
      const gradient = this.ctx.createRadialGradient(
        explosion.x, explosion.y, 0,
        explosion.x, explosion.y, size
      );
      gradient.addColorStop(0, '#f39c12');
      gradient.addColorStop(0.5, '#e74c3c');
      gradient.addColorStop(1, 'transparent');

      this.ctx.fillStyle = gradient;
      this.ctx.beginPath();
      this.ctx.arc(explosion.x, explosion.y, size, 0, Math.PI * 2);
      this.ctx.fill();

      this.ctx.restore();
    });
  }

  /**
   * 绘制子弹轨迹
   */
  drawBulletTrails() {
    this.bulletTrails.forEach(trail => {
      const alpha = trail.life / 10;
      this.ctx.save();
      this.ctx.globalAlpha = alpha;

      this.ctx.strokeStyle = '#f39c12';
      this.ctx.lineWidth = 2;
      this.ctx.beginPath();
      this.ctx.moveTo(trail.x, trail.y);
      this.ctx.lineTo(trail.x - trail.dx * 10, trail.y - trail.dy * 10);
      this.ctx.stroke();

      this.ctx.restore();
    });
  }

  /**
   * 绘制准星
   */
  drawCrosshair() {
    this.ctx.save();
    this.ctx.strokeStyle = '#e74c3c';
    this.ctx.lineWidth = 2;

    const size = 15;

    // 绘制十字准星
    this.ctx.beginPath();
    this.ctx.moveTo(this.mouse.x - size, this.mouse.y);
    this.ctx.lineTo(this.mouse.x + size, this.mouse.y);
    this.ctx.moveTo(this.mouse.x, this.mouse.y - size);
    this.ctx.lineTo(this.mouse.x, this.mouse.y + size);
    this.ctx.stroke();

    // 绘制中心圆
    this.ctx.beginPath();
    this.ctx.arc(this.mouse.x, this.mouse.y, 3, 0, Math.PI * 2);
    this.ctx.stroke();

    this.ctx.restore();
  }
}

// 初始化游戏
document.addEventListener('DOMContentLoaded', () => {
  new AntiJapaneseWarrior();
}); 